<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  <meta name="google-site-verification" content="XKEVBvaS3n3qpVoP-hQqQ2XJ9t43pt4B7J1sLZgRJG4" />
  
  
  <title>程序人生 | C语言字节对齐问题详解 - 对齐/字节序/位序/网络序等（上） | DBKernel - 专注于分享数据库技术</title>
  <meta name="description" content="本文首发于 2014-07-21 15:32:28  1. 引言考虑下面的结构体定义： 123456typedef struct&amp;#123;    char  c1;    short s;    char  c2;    int   i;&amp;#125;T_FOO;  假设这个结构体的成员在内存中是紧凑排列的，且c1的起始地址是0，则s的地址就是1，c2的地址是3，i的地址是4。 现在，我们编">
<meta property="og:type" content="article">
<meta property="og:title" content="程序人生 | C语言字节对齐问题详解 - 对齐&#x2F;字节序&#x2F;位序&#x2F;网络序等（上）">
<meta property="og:url" content="http://dbkernel.github.io/2014/07/21/c-language-byte-alignment-problem-in-detail-part-1/index.html">
<meta property="og:site_name" content="DBKernel">
<meta property="og:description" content="本文首发于 2014-07-21 15:32:28  1. 引言考虑下面的结构体定义： 123456typedef struct&amp;#123;    char  c1;    short s;    char  c2;    int   i;&amp;#125;T_FOO;  假设这个结构体的成员在内存中是紧凑排列的，且c1的起始地址是0，则s的地址就是1，c2的地址是3，i的地址是4。 现在，我们编">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://dbkernel-1306518848.cos.ap-beijing.myqcloud.com/wechat/my-wechat-official-account.png">
<meta property="article:published_time" content="2014-07-21T07:32:28.000Z">
<meta property="article:modified_time" content="2021-09-24T03:55:34.876Z">
<meta property="article:author" content="DBKernel">
<meta property="article:tag" content="C语言">
<meta property="article:tag" content="字节对齐">
<meta property="article:tag" content="字节序">
<meta property="article:tag" content="网络序">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://dbkernel-1306518848.cos.ap-beijing.myqcloud.com/wechat/my-wechat-official-account.png">
  <!-- Canonical links -->
  <link rel="canonical" href="http://dbkernel.github.io/2014/07/21/c-language-byte-alignment-problem-in-detail-part-1/index.html">
  
    <link rel="alternate" href="/atom.xml" title="DBKernel" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="../../../../css/style.css">

  
  
  
  
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.css">
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body class="main-center" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://github.com/dbkernel" target="_blank">
          <img class="img-circle img-rotate" src="../../../../images/avatar.png" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">DBKernel</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">资深数据库开发工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Beijing, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav ">
        
        
        <li class="menu-item menu-item-home">
          <a href="../../../../.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="../../../../archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="../../../../categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="../../../../tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="../../../../repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">项目</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="../../../../links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="../../../../about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="../../../../https:/github.com/dbkernel" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="../../../../atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>本站专注于分享关系型数据库及分布式数据库相关技术！如需深入交流，可添加我的微信或关注我的公众号数据库内核：</br><img src="/images/wechat-me.jpeg" width="130" height="130"/> <img src="/images/wechat-gzh.jpeg" width="130" height="130"/></p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="../../../../categories/ClickHouse/">ClickHouse</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/C%E8%AF%AD%E8%A8%80/">C语言</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/GreenPlum/">GreenPlum</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/Linux/">Linux</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/MySQL/">MySQL</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/PostgreSQL/">PostgreSQL</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/Postgres-X2/">Postgres-X2</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/%E7%BC%96%E8%AF%91%E8%B0%83%E8%AF%95/">编译调试</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="../../../../categories/%E9%80%9A%E7%94%A8/">通用</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/APUE/" rel="tag">APUE</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/B-Tree/" rel="tag">B-Tree</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/ClickHouse/" rel="tag">ClickHouse</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/ClickHouse%E5%92%8C%E4%BB%96%E7%9A%84%E6%9C%8B%E5%8F%8B%E4%BB%AC/" rel="tag">ClickHouse和他的朋友们</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Count/" rel="tag">Count</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/C%E8%AF%AD%E8%A8%80/" rel="tag">C语言</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/DAG-Scheduler/" rel="tag">DAG Scheduler</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/GreenPlum/" rel="tag">GreenPlum</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/HEAP%E5%BC%95%E6%93%8E/" rel="tag">HEAP引擎</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/LICENCE/" rel="tag">LICENCE</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/LSM-Tree/" rel="tag">LSM-Tree</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Linux/" rel="tag">Linux</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/MEMORY%E5%BC%95%E6%93%8E/" rel="tag">MEMORY引擎</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Makefile/" rel="tag">Makefile</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Materialized-View/" rel="tag">Materialized View</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/MergeTree/" rel="tag">MergeTree</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/MySQL/" rel="tag">MySQL</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Parser/" rel="tag">Parser</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Percona/" rel="tag">Percona</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/PostgreSQL/" rel="tag">PostgreSQL</a><span class="tag-list-count">11</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Postgres-X2/" rel="tag">Postgres-X2</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Postgres-XC/" rel="tag">Postgres-XC</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/RadonDB/" rel="tag">RadonDB</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/ReplicatedMergeTree/" rel="tag">ReplicatedMergeTree</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Select/" rel="tag">Select</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/UNIX/" rel="tag">UNIX</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/WAL/" rel="tag">WAL</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Xenon/" rel="tag">Xenon</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/Xtrabackup/" rel="tag">Xtrabackup</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/auto-increment/" rel="tag">auto_increment</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/crontab/" rel="tag">crontab</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/daemon/" rel="tag">daemon</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/df/" rel="tag">df</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/du/" rel="tag">du</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/gcc/" rel="tag">gcc</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/gcov/" rel="tag">gcov</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/getopt/" rel="tag">getopt</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/github/" rel="tag">github</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/group-by/" rel="tag">group by</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/lcov/" rel="tag">lcov</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/libpq/" rel="tag">libpq</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/pg-constraint/" rel="tag">pg_constraint</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/pg-depend/" rel="tag">pg_depend</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/pgbench/" rel="tag">pgbench</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/pipeline/" rel="tag">pipeline</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/processor/" rel="tag">processor</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/shell/" rel="tag">shell</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5/" rel="tag">主从同步</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E4%BC%98%E5%8C%96%E5%99%A8/" rel="tag">优化器</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D/" rel="tag">内存分配</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" rel="tag">内存管理</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%9B%9E%E5%BD%92%E6%B5%8B%E8%AF%95/" rel="tag">回归测试</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%AD%97%E8%8A%82%E5%AF%B9%E9%BD%90/" rel="tag">字节对齐</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%AD%97%E8%8A%82%E5%BA%8F/" rel="tag">字节序</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%AD%98%E5%82%A8%E8%AE%A1%E7%AE%97%E5%88%86%E7%A6%BB/" rel="tag">存储计算分离</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%B9%B6%E8%A1%8C%E6%9F%A5%E8%AF%A2/" rel="tag">并行查询</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%BC%80%E6%BA%90%E5%8D%8F%E8%AE%AE/" rel="tag">开源协议</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E5%BC%80%E6%BA%90%E8%AE%B8%E5%8F%AF%E8%AF%81/" rel="tag">开源许可证</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E6%9C%AC%E5%9C%B0%E4%BA%8B%E5%8A%A1/" rel="tag">本地事务</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E6%B5%8B%E8%AF%95/" rel="tag">测试</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" rel="tag">源码分析</a><span class="tag-list-count">15</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E7%B3%BB%E7%BB%9F%E8%BF%90%E7%BB%B4/" rel="tag">系统运维</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E7%BC%96%E8%AF%91%E5%99%A8/" rel="tag">编译器</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E7%BD%91%E7%BB%9C%E5%BA%8F/" rel="tag">网络序</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" rel="tag">网络编程</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="../../../../tags/%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D/" rel="tag">问题定位</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="../../../../tags/APUE/" style="font-size: 13.33px;">APUE</a> <a href="../../../../tags/B-Tree/" style="font-size: 13px;">B-Tree</a> <a href="../../../../tags/ClickHouse/" style="font-size: 13.89px;">ClickHouse</a> <a href="../../../../tags/ClickHouse%E5%92%8C%E4%BB%96%E7%9A%84%E6%9C%8B%E5%8F%8B%E4%BB%AC/" style="font-size: 13.89px;">ClickHouse和他的朋友们</a> <a href="../../../../tags/Count/" style="font-size: 13px;">Count</a> <a href="../../../../tags/C%E8%AF%AD%E8%A8%80/" style="font-size: 13.67px;">C语言</a> <a href="../../../../tags/DAG-Scheduler/" style="font-size: 13px;">DAG Scheduler</a> <a href="../../../../tags/GreenPlum/" style="font-size: 13.22px;">GreenPlum</a> <a href="../../../../tags/HEAP%E5%BC%95%E6%93%8E/" style="font-size: 13px;">HEAP引擎</a> <a href="../../../../tags/LICENCE/" style="font-size: 13px;">LICENCE</a> <a href="../../../../tags/LSM-Tree/" style="font-size: 13px;">LSM-Tree</a> <a href="../../../../tags/Linux/" style="font-size: 13.44px;">Linux</a> <a href="../../../../tags/MEMORY%E5%BC%95%E6%93%8E/" style="font-size: 13px;">MEMORY引擎</a> <a href="../../../../tags/Makefile/" style="font-size: 13px;">Makefile</a> <a href="../../../../tags/Materialized-View/" style="font-size: 13px;">Materialized View</a> <a href="../../../../tags/MergeTree/" style="font-size: 13.11px;">MergeTree</a> <a href="../../../../tags/MySQL/" style="font-size: 13.56px;">MySQL</a> <a href="../../../../tags/Parser/" style="font-size: 13px;">Parser</a> <a href="../../../../tags/Percona/" style="font-size: 13px;">Percona</a> <a href="../../../../tags/PostgreSQL/" style="font-size: 13.78px;">PostgreSQL</a> <a href="../../../../tags/Postgres-X2/" style="font-size: 13px;">Postgres-X2</a> <a href="../../../../tags/Postgres-XC/" style="font-size: 13px;">Postgres-XC</a> <a href="../../../../tags/RadonDB/" style="font-size: 13px;">RadonDB</a> <a href="../../../../tags/ReplicatedMergeTree/" style="font-size: 13px;">ReplicatedMergeTree</a> <a href="../../../../tags/Select/" style="font-size: 13px;">Select</a> <a href="../../../../tags/UNIX/" style="font-size: 13.22px;">UNIX</a> <a href="../../../../tags/WAL/" style="font-size: 13.11px;">WAL</a> <a href="../../../../tags/Xenon/" style="font-size: 13px;">Xenon</a> <a href="../../../../tags/Xtrabackup/" style="font-size: 13px;">Xtrabackup</a> <a href="../../../../tags/auto-increment/" style="font-size: 13px;">auto_increment</a> <a href="../../../../tags/crontab/" style="font-size: 13px;">crontab</a> <a href="../../../../tags/daemon/" style="font-size: 13px;">daemon</a> <a href="../../../../tags/df/" style="font-size: 13px;">df</a> <a href="../../../../tags/du/" style="font-size: 13px;">du</a> <a href="../../../../tags/gcc/" style="font-size: 13px;">gcc</a> <a href="../../../../tags/gcov/" style="font-size: 13px;">gcov</a> <a href="../../../../tags/getopt/" style="font-size: 13px;">getopt</a> <a href="../../../../tags/github/" style="font-size: 13px;">github</a> <a href="../../../../tags/group-by/" style="font-size: 13px;">group by</a> <a href="../../../../tags/lcov/" style="font-size: 13px;">lcov</a> <a href="../../../../tags/libpq/" style="font-size: 13px;">libpq</a> <a href="../../../../tags/pg-constraint/" style="font-size: 13px;">pg_constraint</a> <a href="../../../../tags/pg-depend/" style="font-size: 13px;">pg_depend</a> <a href="../../../../tags/pgbench/" style="font-size: 13px;">pgbench</a> <a href="../../../../tags/pipeline/" style="font-size: 13px;">pipeline</a> <a href="../../../../tags/processor/" style="font-size: 13px;">processor</a> <a href="../../../../tags/shell/" style="font-size: 13px;">shell</a> <a href="../../../../tags/%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5/" style="font-size: 13.11px;">主从同步</a> <a href="../../../../tags/%E4%BC%98%E5%8C%96%E5%99%A8/" style="font-size: 13px;">优化器</a> <a href="../../../../tags/%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D/" style="font-size: 13px;">内存分配</a> <a href="../../../../tags/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" style="font-size: 13px;">内存管理</a> <a href="../../../../tags/%E5%9B%9E%E5%BD%92%E6%B5%8B%E8%AF%95/" style="font-size: 13px;">回归测试</a> <a href="../../../../tags/%E5%AD%97%E8%8A%82%E5%AF%B9%E9%BD%90/" style="font-size: 13.11px;">字节对齐</a> <a href="../../../../tags/%E5%AD%97%E8%8A%82%E5%BA%8F/" style="font-size: 13.11px;">字节序</a> <a href="../../../../tags/%E5%AD%98%E5%82%A8%E8%AE%A1%E7%AE%97%E5%88%86%E7%A6%BB/" style="font-size: 13px;">存储计算分离</a> <a href="../../../../tags/%E5%B9%B6%E8%A1%8C%E6%9F%A5%E8%AF%A2/" style="font-size: 13px;">并行查询</a> <a href="../../../../tags/%E5%BC%80%E6%BA%90%E5%8D%8F%E8%AE%AE/" style="font-size: 13px;">开源协议</a> <a href="../../../../tags/%E5%BC%80%E6%BA%90%E8%AE%B8%E5%8F%AF%E8%AF%81/" style="font-size: 13px;">开源许可证</a> <a href="../../../../tags/%E6%9C%AC%E5%9C%B0%E4%BA%8B%E5%8A%A1/" style="font-size: 13px;">本地事务</a> <a href="../../../../tags/%E6%B5%8B%E8%AF%95/" style="font-size: 13px;">测试</a> <a href="../../../../tags/%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" style="font-size: 14px;">源码分析</a> <a href="../../../../tags/%E7%B3%BB%E7%BB%9F%E8%BF%90%E7%BB%B4/" style="font-size: 13px;">系统运维</a> <a href="../../../../tags/%E7%BC%96%E8%AF%91%E5%99%A8/" style="font-size: 13px;">编译器</a> <a href="../../../../tags/%E7%BD%91%E7%BB%9C%E5%BA%8F/" style="font-size: 13.11px;">网络序</a> <a href="../../../../tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" style="font-size: 13px;">网络编程</a> <a href="../../../../tags/%E9%97%AE%E9%A2%98%E5%AE%9A%E4%BD%8D/" style="font-size: 13.11px;">问题定位</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2021/08/">八月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2021/01/">一月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2020/09/">九月 2020</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2020/08/">八月 2020</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2020/07/">七月 2020</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2020/06/">六月 2020</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2020/05/">五月 2020</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2019/12/">十二月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2019/04/">四月 2019</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2018/09/">九月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2016/11/">十一月 2016</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2016/04/">四月 2016</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2016/03/">三月 2016</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2016/01/">一月 2016</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2015/12/">十二月 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2015/11/">十一月 2015</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2015/05/">五月 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2015/01/">一月 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2014/08/">八月 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2014/07/">七月 2014</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2014/03/">三月 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="../../../../archives/2014/01/">一月 2014</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="../../../../categories/%E9%80%9A%E7%94%A8/">通用</a>
              </p>
              <p class="item-title">
                <a href="../../../../2021/08/19/how-to-choose-open-source-licence/" class="title">技术分享 | 如何为你的代码选择一个合适的开源协议？</a>
              </p>
              <p class="item-date">
                <time datetime="2021-08-18T16:37:15.000Z" itemprop="datePublished">2021-08-19</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="../../../../categories/ClickHouse/">ClickHouse</a>
              </p>
              <p class="item-title">
                <a href="../../../../2021/01/26/clickhouse-and-friends-15-groupby/" class="title">源码分析 | ClickHouse和他的朋友们（15）Group By 为什么这么快</a>
              </p>
              <p class="item-date">
                <time datetime="2021-01-26T13:31:12.000Z" itemprop="datePublished">2021-01-26</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="../../../../categories/ClickHouse/">ClickHouse</a>
              </p>
              <p class="item-title">
                <a href="../../../../2020/09/21/clickhouse-and-friends-14-compute-storage/" class="title">源码分析 | ClickHouse和他的朋友们（14）存储计算分离方案与实现</a>
              </p>
              <p class="item-date">
                <time datetime="2020-09-21T14:01:12.000Z" itemprop="datePublished">2020-09-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="../../../../categories/ClickHouse/">ClickHouse</a>
              </p>
              <p class="item-title">
                <a href="../../../../2020/09/15/clickhouse-and-friends-13-replicated-merge-tree/" class="title">源码分析 | ClickHouse和他的朋友们（13）ReplicatedMergeTree表引擎及同步机制</a>
              </p>
              <p class="item-date">
                <time datetime="2020-09-15T12:15:14.000Z" itemprop="datePublished">2020-09-15</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="../../../../categories/ClickHouse/">ClickHouse</a>
              </p>
              <p class="item-title">
                <a href="../../../../2020/09/03/clickhouse-and-friends-12-materialized-view/" class="title">源码分析 | ClickHouse和他的朋友们（12）神奇的物化视图(Materialized View)与原理</a>
              </p>
              <p class="item-date">
                <time datetime="2020-09-03T13:22:14.000Z" itemprop="datePublished">2020-09-03</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E5%BC%95%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">1. 引言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-%E4%BB%80%E4%B9%88%E6%98%AF%E5%AD%97%E8%8A%82%E5%AF%B9%E9%BD%90"><span class="toc-number">2.</span> <span class="toc-text">2. 什么是字节对齐</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-%E5%AF%B9%E9%BD%90%E7%9A%84%E5%8E%9F%E5%9B%A0%E5%92%8C%E4%BD%9C%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">3. 对齐的原因和作用</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-%E5%AF%B9%E9%BD%90%E7%9A%84%E5%88%86%E7%B1%BB%E5%92%8C%E5%87%86%E5%88%99"><span class="toc-number">4.</span> <span class="toc-text">4. 对齐的分类和准则</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-%E7%BB%93%E6%9E%84%E4%BD%93%E5%AF%B9%E9%BD%90"><span class="toc-number">4.1.</span> <span class="toc-text">4.1. 结构体对齐</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-1-%E7%AE%80%E5%8D%95%E7%A4%BA%E4%BE%8B"><span class="toc-number">4.1.1.</span> <span class="toc-text">4.1.1. 简单示例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-2-%E5%AF%B9%E9%BD%90%E5%87%86%E5%88%99"><span class="toc-number">4.1.2.</span> <span class="toc-text">4.1.2. 对齐准则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-3-%E5%AF%B9%E9%BD%90%E7%9A%84%E9%9A%90%E6%82%A3"><span class="toc-number">4.1.3.</span> <span class="toc-text">4.1.3. 对齐的隐患</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-1-3-1-%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="toc-number">4.1.3.1.</span> <span class="toc-text">4.1.3.1. 数据类型转换</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-1-3-2-%E5%A4%84%E7%90%86%E5%99%A8%E9%97%B4%E6%95%B0%E6%8D%AE%E9%80%9A%E4%BF%A1"><span class="toc-number">4.1.3.2.</span> <span class="toc-text">4.1.3.2. 处理器间数据通信</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-1-3-3-%E6%8E%92%E6%9F%A5%E5%AF%B9%E9%BD%90%E9%97%AE%E9%A2%98"><span class="toc-number">4.1.3.3.</span> <span class="toc-text">4.1.3.3. 排查对齐问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-4-%E6%9B%B4%E6%94%B9%E5%AF%B9%E9%BD%90%E6%96%B9%E5%BC%8F"><span class="toc-number">4.1.4.</span> <span class="toc-text">4.1.4. 更改对齐方式</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-2-%E6%A0%88%E5%86%85%E5%AD%98%E5%AF%B9%E9%BD%90"><span class="toc-number">4.2.</span> <span class="toc-text">4.2. 栈内存对齐</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-3-%E4%BD%8D%E5%9F%9F%E5%AF%B9%E9%BD%90"><span class="toc-number">4.3.</span> <span class="toc-text">4.3. 位域对齐</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-1-%E4%BD%8D%E5%9F%9F%E5%AE%9A%E4%B9%89"><span class="toc-number">4.3.1.</span> <span class="toc-text">4.3.1. 位域定义</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-2-%E5%AF%B9%E9%BD%90%E5%87%86%E5%88%99"><span class="toc-number">4.3.2.</span> <span class="toc-text">4.3.2. 对齐准则</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-3-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-number">4.3.3.</span> <span class="toc-text">4.3.3. 注意事项</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-%E6%80%BB%E7%BB%93"><span class="toc-number">5.</span> <span class="toc-text">5. 总结</span></a></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-c-language-byte-alignment-problem-in-detail-part-1" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      程序人生 | C语言字节对齐问题详解 - 对齐/字节序/位序/网络序等（上）
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="" class="article-date">
	  <time datetime="2014-07-21T07:32:28.000Z" itemprop="datePublished">2014-07-21</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="../../../../categories/C%E8%AF%AD%E8%A8%80/">C语言</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="../../../../tags/C%E8%AF%AD%E8%A8%80/" rel="tag">C语言</a>, <a class="article-tag-link-link" href="../../../../tags/%E5%AD%97%E8%8A%82%E5%AF%B9%E9%BD%90/" rel="tag">字节对齐</a>, <a class="article-tag-link-link" href="../../../../tags/%E5%AD%97%E8%8A%82%E5%BA%8F/" rel="tag">字节序</a>, <a class="article-tag-link-link" href="../../../../tags/%E7%BD%91%E7%BB%9C%E5%BA%8F/" rel="tag">网络序</a>
  </span>


        
	<span class="article-read hidden-xs">
	    <i class="icon icon-eye-fill" aria-hidden="true"></i>
	    <span id="busuanzi_container_page_pv">
			<span id="busuanzi_value_page_pv">0</span>
		</span>
	</span>


        <span class="post-comment"><i class="icon icon-comment"></i> <a href="#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 7.3k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 27(分)</span>
	

      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <span id="more"></span>

<blockquote>
<p><strong>本文首发于 2014-07-21 15:32:28</strong></p>
</blockquote>
<h1 id="1-引言"><a href="#1-引言" class="headerlink" title="1. 引言"></a>1. 引言</h1><p>考虑下面的结构体定义：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>  c1;</span><br><span class="line">    <span class="keyword">short</span> s;</span><br><span class="line">    <span class="keyword">char</span>  c2;</span><br><span class="line">    <span class="keyword">int</span>   i;</span><br><span class="line">&#125;T_FOO;</span><br></pre></td></tr></table></figure>

<p>假设这个结构体的成员在内存中是紧凑排列的，且c1的起始地址是0，则s的地址就是1，c2的地址是3，i的地址是4。</p>
<p>现在，我们编写一个简单的程序：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    T_FOO a;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;c1 -&gt; %d, s -&gt; %d, c2 -&gt; %d, i -&gt; %d\n&quot;</span>,</span><br><span class="line">          (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a.c1 - (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a,</span><br><span class="line">          (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a.s  - (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a,</span><br><span class="line">          (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a.c2 - (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a,</span><br><span class="line">          (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a.i  - (<span class="keyword">unsigned</span> <span class="keyword">int</span>)(<span class="keyword">void</span>*)&amp;a);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行后输出：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c1 -&gt; <span class="number">0</span>, s -&gt; <span class="number">2</span>, c2 -&gt; <span class="number">4</span>, i -&gt; <span class="number">8</span></span><br></pre></td></tr></table></figure>

<p>为什么会这样？这就是字节对齐导致的问题。</p>
<p>本文在参考诸多资料的基础上，详细介绍常见的字节对齐问题。因成文较早，资料来源大多已不可考，敬请谅解。</p>
<h1 id="2-什么是字节对齐"><a href="#2-什么是字节对齐" class="headerlink" title="2. 什么是字节对齐"></a>2. 什么是字节对齐</h1><p>现代计算机中，内存空间按照字节划分，理论上可以从任何起始地址访问任意类型的变量，但实际上在访问特定类型变量时经常在特定的内存地址访问，这就需要各种类型数据按照一定的规则在空间上排列，而不是一个接一个地顺序存放，这就是对齐。</p>
<h1 id="3-对齐的原因和作用"><a href="#3-对齐的原因和作用" class="headerlink" title="3. 对齐的原因和作用"></a>3. 对齐的原因和作用</h1><ol>
<li><strong>不同硬件平台对存储空间的处理上存在很大的不同</strong>。某些平台对特定类型的数据只能从特定地址开始存取，而不允许其在内存中任意存放。例如 Motorola 68000 处理器不允许16位的字存放在奇地址，否则会触发异常，因此在这种架构下编程必须保证字节对齐。</li>
<li><strong>如果不按照平台要求对数据存放进行对齐，会带来存取效率上的损失</strong>。比如32位的 Intel 处理器通过总线访问(包括读和写)内存数据。每个总线周期从偶地址开始访问32位内存数据，内存数据以字节为单位存放。如果一个32位的数据没有存放在4字节整除的内存地址处，那么处理器就需要2个总线周期对其进行访问，显然访问效率下降很多。因此，<strong>通过合理的内存对齐可以提高访问效率。</strong> 为使CPU能够对数据进行快速访问，数据的起始地址应具有“对齐”特性。比如4字节数据的起始地址应位于4字节边界上，即起始地址能够被4整除。</li>
<li><strong>合理利用字节对齐还可以有效地节省存储空间</strong>。但要注意，在32位机中使用1字节或2字节对齐，反而会降低变量访问速度，因此，<strong>需要考虑处理器类型</strong>。同时，<strong>还应考虑编译器的类型</strong>，<code>在VC/C++和GNU GCC中都是默认是4字节对齐</code>。</li>
</ol>
<h1 id="4-对齐的分类和准则"><a href="#4-对齐的分类和准则" class="headerlink" title="4. 对齐的分类和准则"></a>4. 对齐的分类和准则</h1><p>本小节主要基于 Intel X86 架构介绍结构体对齐和栈内存对齐，<strong>位域</strong>本质上为结构体类型。</p>
<p><strong>对于 Intel X86 平台，每次分配内存应该是从4的整数倍地址开始分配，无论是对结构体变量还是简单类型的变量。</strong></p>
<h2 id="4-1-结构体对齐"><a href="#4-1-结构体对齐" class="headerlink" title="4.1. 结构体对齐"></a>4.1. 结构体对齐</h2><p>在C语言中，结构体是种复合数据类型，其构成元素既可以是基本数据类型（int、long、float等）的变量，也可以是一些复合数据类型（数组、结构体、联合等)的数据单元。编译器为结构体的每个成员按照其自然边界（alignment）分配空间。各成员按照它们被声明的顺序在内存中顺序存储，<strong>第一个成员的地址和整个结构的地址相同。</strong></p>
<p>字节对齐的问题主要就是针对结构体。</p>
<h3 id="4-1-1-简单示例"><a href="#4-1-1-简单示例" class="headerlink" title="4.1.1. 简单示例"></a>4.1.1. 简单示例</h3><p>先看个简单的例子（32位，X86处理器，GCC编译器）：</p>
<p>【例1】假设结构体定义如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">A</span>&#123;</span></span><br><span class="line">    <span class="keyword">int</span>    a;</span><br><span class="line">    <span class="keyword">char</span>   b;</span><br><span class="line">    <span class="keyword">short</span>  c;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">B</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>   b;</span><br><span class="line">    <span class="keyword">int</span>    a;</span><br><span class="line">    <span class="keyword">short</span>  c;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>已知32位机器上各数据类型的长度为：char为1字节、short为2字节、int为4字节、long为4字节、float为4字节、double为8字节。那么上面两个结构体大小如何呢？</p>
<p>结果是：<strong>sizeof(strcut A)值为8；sizeof(struct B)的值却是12</strong>。</p>
<p>结构体A和B中字段一样，包含一个4字节的int数据，一个1字节char数据和一个2字节short数据，只是顺序不同。按理说A和B大小应该都是7字节，之所以出现上述结果，就是因为编译器要对数据成员在空间上进行对齐。</p>
<h3 id="4-1-2-对齐准则"><a href="#4-1-2-对齐准则" class="headerlink" title="4.1.2. 对齐准则"></a>4.1.2. 对齐准则</h3><p>先来看四个重要的基本概念：</p>
<ol>
<li><p><strong>数据类型自身的对齐值</strong>：char型数据自身对齐值为1字节，short型数据为2字节，int/float型为4字节，double型为8字节。</p>
</li>
<li><p><strong>结构体或类的自身对齐值</strong>：<code>其成员中自身对齐值最大的那个值</code>。</p>
</li>
<li><p><strong>指定对齐值</strong>：<code>#pragma pack (value)</code> 指定对齐值 value。</p>
</li>
<li><p><strong>数据成员、结构体和类的有效对齐值</strong>：自身对齐值和指定对齐值中较小者，即<code>有效对齐值=min&#123;自身对齐值，当前指定的pack值&#125;</code>。</p>
</li>
</ol>
<p>基于上面这些原则，就可以方便地讨论具体数据结构的成员和其自身的对齐方式。</p>
<p>其中，有效对齐值 N 是最终用来决定数据存放地址方式的值。有效对齐值 N 表示“对齐在N上”，即该数据的<code>存放起始地址 % N = 0</code>。而数据结构中的数据变量都是按定义的先后顺序存放。第一个数据变量的起始地址就是数据结构的起始地址。<strong>结构体的成员变量要对齐存放，结构体本身也要根据自身的有效对齐值圆整</strong>（即<code>结构体成员变量占用总长度为结构体有效对齐值的整数倍</code>）。</p>
<p>以此分析3.1.1节中的结构体B：</p>
<blockquote>
<p>假设B从地址空间0x0000开始存放，且指定对齐值默认为4(4字节对齐)。成员变量b的自身对齐值是1，比默认指定对齐值4小，所以其有效对齐值为1，其存放地址0x0000符合0x0000%1=0。</p>
<p>成员变量a自身对齐值为4，所以有效对齐值也为4，只能存放在起始地址为0x0004~0x0007四个连续的字节空间中，符合0x0004%4=0且紧靠第一个变量。</p>
<p>变量c自身对齐值为2，所以有效对齐值也是2，可存放在0x0008~0x0009两个字节空间中，符合0x0008%2=0。</p>
<p>所以从0x0000~0x0009存放的都是B内容。</p>
<p>再看数据结构B的自身对齐值为其变量中最大对齐值（这里是b），也就是4，所以结构体的有效对齐值也是4。<strong>根据结构体圆整的要求，0x0000~0x0009=10字节，(10＋2)％4＝0</strong>。</p>
<p>所以0x0000A~0x000B也为结构体B所占用。故B从0x0000到0x000B，共有12个字节，sizeof(struct B)=12。</p>
</blockquote>
<p><strong>之所以编译器在后面补充2个字节，是为了实现结构数组的存取效率</strong>。试想如果定义一个结构B的数组，那么第一个结构起始地址是0没有问题，但是第二个结构呢？</p>
<p>按照数组的定义，数组中所有元素都紧挨着。如果我们不把结构体大小补充为4的整数倍，那么下一个结构的起始地址将是0x0000A，这显然不能满足结构的地址对齐。因此要把结构体补充成有效对齐大小的整数倍。</p>
<p>其实对于char/short/int/float/double等已有类型的自身对齐值也是基于数组考虑的，只是因为这些类型的长度已知，所以他们的自身对齐值也就已知。</p>
<p>上面的概念非常便于理解，不过个人还是更喜欢下面的对齐准则。</p>
<p><strong>结构体字节对齐的细节和具体编译器实现相关，但一般而言满足三个准则：</strong></p>
<ol>
<li><strong>结构体变量的首地址能够被其最宽基本类型成员的大小所整除；</strong></li>
<li><strong>结构体每个成员相对结构体首地址的偏移量(offset)都是成员大小的整数倍，如有需要编译器会在成员之间加上填充字节(internal adding)；</strong></li>
<li><strong>结构体的总大小为结构体最宽基本类型成员大小的整数倍，如有需要编译器会在最末一个成员之后加上填充字节{trailing padding}。</strong></li>
</ol>
<p>对于以上规则的说明如下：</p>
<ul>
<li>第一条：编译器在给结构体开辟空间时，首先找到结构体中最宽的基本数据类型，然后寻找内存地址能被该基本数据类型所整除的位置，作为结构体的首地址。<code>将这个最宽的基本数据类型的大小作为上面介绍的对齐模数</code>。</li>
<li>第二条：为结构体的一个成员开辟空间之前，<code>编译器首先检查预开辟空间的首地址相对于结构体首地址的偏移是否是本成员大小的整数倍</code>，若是，则存放本成员，反之，则在本成员和上一个成员之间填充一定的字节，以达到整数倍的要求，也就是将预开辟空间的首地址后移几个字节。</li>
<li>第三条：<code>结构体总大小是包括填充字节</code>，最后一个成员满足上面两条以外，还必须满足第三条，否则就必须在最后填充几个字节以达到本条要求。</li>
</ul>
<p>【例2】假设4字节对齐，以下程序的输出结果是多少？</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* OFFSET宏定义可取得指定结构体某成员在结构体内部的偏移 */</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> OFFSET(st, field) (size_t)&amp;(((st*)0)-&gt;field)</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>  a;</span><br><span class="line">    <span class="keyword">short</span> b;</span><br><span class="line">    <span class="keyword">char</span>  c;</span><br><span class="line">    <span class="keyword">int</span>   d;</span><br><span class="line">    <span class="keyword">char</span>  e[<span class="number">3</span>];</span><br><span class="line">&#125;T_Test;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Size = %d\n  a-%d, b-%d, c-%d, d-%d\n  e[0]-%d, e[1]-%d, e[2]-%d\n&quot;</span>,</span><br><span class="line">           <span class="built_in"><span class="keyword">sizeof</span></span>(T_Test), <span class="built_in">OFFSET</span>(T_Test, a), <span class="built_in">OFFSET</span>(T_Test, b),</span><br><span class="line">           <span class="built_in">OFFSET</span>(T_Test, c), <span class="built_in">OFFSET</span>(T_Test, d), <span class="built_in">OFFSET</span>(T_Test, e[<span class="number">0</span>]),</span><br><span class="line">           <span class="built_in">OFFSET</span>(T_Test, e[<span class="number">1</span>]),<span class="built_in">OFFSET</span>(T_Test, e[<span class="number">2</span>]));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>执行后输出如下：</strong></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Size = 16</span><br><span class="line">a-0, b-2, c-4, d-8</span><br><span class="line">e[0]-12, e[1]-13, e[2]-14</span><br></pre></td></tr></table></figure>

<p><strong>下面来具体分析：</strong></p>
<blockquote>
<p>首先char a占用1个字节，没问题。</p>
<p>short b本身占用2个字节，根据上面准则2，需要在b和a之间填充1个字节。</p>
<p>char c占用1个字节，没问题。</p>
<p>int d本身占用4个字节，根据准则2，需要在d和c之间填充3个字节。</p>
<p>char e[3]；本身占用3个字节，根据原则3，需要在其后补充1个字节。</p>
<p>因此，sizeof(T_Test) = 1 + 1 + 2 + 1 + 3 + 4 + 3 + 1 = 16字节。</p>
</blockquote>
<h3 id="4-1-3-对齐的隐患"><a href="#4-1-3-对齐的隐患" class="headerlink" title="4.1.3. 对齐的隐患"></a>4.1.3. 对齐的隐患</h3><h4 id="4-1-3-1-数据类型转换"><a href="#4-1-3-1-数据类型转换" class="headerlink" title="4.1.3.1. 数据类型转换"></a>4.1.3.1. 数据类型转换</h4><p><strong>代码中关于对齐的隐患，很多是隐式的</strong>。例如，在强制类型转换的时候：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">int</span> i = <span class="number">0x12345678</span>;</span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">char</span> *p = (<span class="keyword">unsigned</span> <span class="keyword">char</span> *)&amp;i;</span><br><span class="line">    *p = <span class="number">0x00</span>;</span><br><span class="line">    <span class="keyword">unsigned</span> <span class="keyword">short</span> *p1 = (<span class="keyword">unsigned</span> <span class="keyword">short</span> *)(p+<span class="number">1</span>);</span><br><span class="line">    *p1 = <span class="number">0x0000</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后两句代码，<code>从奇数边界去访问 unsigned short 型变量，显然不符合对齐的规定。在X86上，类似的操作只会影响效率；但在MIPS或者SPARC上可能导致error，因为它们要求必须字节对齐</code>。</p>
<p>又如对于3.1.1节的结构体 struct B，定义如下函数：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Func</span><span class="params">(struct B *p)</span></span>&#123;</span><br><span class="line">     <span class="comment">//Code</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在函数体内如果直接访问 p-&gt;a，则很可能会异常。因为MIPS认为a是int，其地址应该是4的倍数，但p-&gt;a的地址很可能不是4的倍数。</p>
<p><strong>如果p的地址不在对齐边界上就可能出问题</strong>，比如p来自一个跨CPU的数据包(多种数据类型的数据被按顺序放置在一个数据包中传输)，或p是经过指针移位算出来的。因此要特别注意跨CPU数据的接口函数对接口输入数据的处理，以及指针移位再强制转换为结构指针进行访问时的安全性。</p>
<p><strong>解决方式如下：</strong></p>
<ol>
<li>定义一个此结构的局部变量，用<code>memmove</code>方式将数据拷贝进来。<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Func</span><span class="params">(struct B *p)</span></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">B</span> <span class="title">tData</span>;</span></span><br><span class="line">    <span class="built_in">memmove</span>(&amp;tData, p, <span class="built_in"><span class="keyword">sizeof</span></span>(struct B));</span><br><span class="line">     <span class="comment">//此后可安全访问tData.a，因为编译器已将tData分配在正确的起始地址上</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
注意：<strong>如果能确定p的起始地址没问题，则不需要这么处理；如果不能确定（比如跨CPU输入数据、或指针移位运算出来的数据），则需要这样处理。</strong></li>
<li>用<code>#pragma pack (1)</code>将 STRUCT_T 定义为1字节对齐方式。</li>
</ol>
<h4 id="4-1-3-2-处理器间数据通信"><a href="#4-1-3-2-处理器间数据通信" class="headerlink" title="4.1.3.2. 处理器间数据通信"></a>4.1.3.2. 处理器间数据通信</h4><p><strong>处理器间通过消息（对于C/C++而言就是结构体）进行通信时，需要注意字节对齐以及字节序的问题。</strong></p>
<p>大多数编译器提供一些内存选项供用户使用。这样用户可以根据处理器的情况选择不同的字节对齐方式。例如：C/C++编译器提供的<code>#pragma pack(n) n=1，2，4</code>等，让编译器在生成目标文件时，<code>使内存数据按照指定的方式排布在1，2，4等字节整除的内存地址处</code>。</p>
<p>然而在不同编译平台或处理器上，字节对齐会造成消息结构长度的变化。<strong>编译器为了使字节对齐可能会对消息结构体进行填充，不同编译平台可能填充为不同的形式，大大增加处理器间数据通信的风险。</strong></p>
<p>下面以32位处理器为例，提出一种内存对齐方法以解决上述问题。</p>
<p>对于本地使用的数据结构，为提高内存访问效率，采用4字节对齐方式；同时为了减少内存的开销，合理安排结构体成员的位置，减少4字节对齐导致的成员之间的空隙，降低内存开销。</p>
<p>对于处理器之间的数据结构，需要保证消息长度不会因不同编译平台或处理器而导致消息结构体长度发生变化，使用1字节对齐方式对消息结构进行紧缩；为保证处理器之间的消息数据结构的内存访问效率，采用字节填充的方式自己对消息中成员进行4字节对齐。</p>
<p>数据结构的成员位置要兼顾成员之间的关系、数据访问效率和空间利用率。<strong>顺序安排原则是：4字节的放在最前面，2字节的紧接最后一个4字节成员，1字节紧接最后一个2字节成员，填充字节放在最后。</strong></p>
<p>举例如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> <span class="title">tag_T_MSG</span>&#123;</span></span><br><span class="line">    <span class="keyword">long</span>  ParaA;</span><br><span class="line">    <span class="keyword">long</span>  ParaB;</span><br><span class="line">    <span class="keyword">short</span> ParaC；</span><br><span class="line">    <span class="keyword">char</span>  ParaD;</span><br><span class="line">    <span class="keyword">char</span>  Pad;   <span class="comment">//填充字节</span></span><br><span class="line">&#125;T_MSG;</span><br></pre></td></tr></table></figure>

<h4 id="4-1-3-3-排查对齐问题"><a href="#4-1-3-3-排查对齐问题" class="headerlink" title="4.1.3.3. 排查对齐问题"></a>4.1.3.3. 排查对齐问题</h4><p>如果出现对齐或者赋值问题，可查看：</p>
<ol>
<li>编译器的字节序大小端设置；</li>
<li>处理器架构本身是否支持非对齐访问；<blockquote>
<p>如果支持，则看是否设置对齐；</p>
<p>如果没有，则看访问时是否需要加某些特殊的修饰来标志其特殊访问操作。</p>
</blockquote>
</li>
</ol>
<h3 id="4-1-4-更改对齐方式"><a href="#4-1-4-更改对齐方式" class="headerlink" title="4.1.4. 更改对齐方式"></a>4.1.4. 更改对齐方式</h3><p>主要是<strong>更改C编译器的缺省字节对齐方式</strong>。</p>
<p>在缺省情况下，C编译器为每一个变量或是数据单元按其自然对界条件分配空间。一般地，可以通过下面的方法来改变缺省的对界条件：</p>
<ul>
<li>使用<code>伪指令#pragma pack(n)</code>：C编译器将按照n个字节对齐；</li>
<li>使用<code>伪指令#pragma pack()</code>：取消自定义字节对齐方式。</li>
</ul>
<p>另外，还有如下的一种方式（GCC特有语法）：</p>
<ul>
<li><code>__attribute__((aligned (n)))</code>：让所作用的结构成员对齐在n字节自然边界上。如果结构体中有成员的长度大于n，则按照最大成员的长度来对齐。</li>
<li><code>__attribute__((packed))</code>：取消结构在编译过程中的优化对齐，按照实际占用字节数进行对齐。</li>
</ul>
<blockquote>
<p><strong>注意：</strong></p>
<p><code>__attribute__</code>机制是GCC的一大特色，可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。</p>
</blockquote>
<p><strong>在编码时，可用<code>#pragma pack</code>动态修改对齐值</strong>。具体语法说明见附录5.3节。</p>
<p>自定义对齐值后要用<code>#pragma pack()</code>来还原，否则会对后面的结构造成影响。</p>
<p>【例3】分析如下结构体C：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(2)  <span class="comment">//指定按2字节对齐</span></span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">C</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>  b;</span><br><span class="line">    <span class="keyword">int</span>   a;</span><br><span class="line">    <span class="keyword">short</span> c;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack()   <span class="comment">//取消指定对齐，恢复缺省对齐</span></span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>变量b自身对齐值为1，指定对齐值为2，所以有效对齐值为1，假设C从0x0000开始，则b存放在0x0000，符合0x0000%1=0；</p>
<p>变量a自身对齐值为4，指定对齐值为2，所以有效对齐值为2，顺序存放在0x0002~0x0005四个连续字节中，符合0x0002%2=0。</p>
<p>变量c的自身对齐值为2，所以有效对齐值为2，顺序存放在0x0006~0x0007中，符合0x0006%2=0。</p>
<p>所以从0x0000到0x00007共8字节存放的是C的变量。</p>
<p>C的自身对齐值为4，所以其有效对齐值为2。又8%2=0，C只占用0x0000~0x0007的八个字节。所以sizeof(struct C)=8。</p>
</blockquote>
<p>注意：<strong>结构体对齐到的字节数并非完全取决于当前指定的pack值</strong>，例如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(8)</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">D</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>  b;</span><br><span class="line">    <span class="keyword">short</span> a;</span><br><span class="line">    <span class="keyword">char</span>  c;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack()</span></span><br></pre></td></tr></table></figure>

<p>虽然<code>#pragma pack(8)</code>，但依然按照2字节对齐，所以 sizeof(struct D) 的值为6。所以，<strong>对齐到的字节数=min｛当前指定的pack值，最大成员大小｝</strong>。</p>
<p>另外，GNU GCC编译器中按1字节对齐可写为以下形式：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> GNUC_PACKED __attribute__((packed))</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">C</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span>  b;</span><br><span class="line">    <span class="keyword">int</span>   a;</span><br><span class="line">    <span class="keyword">short</span> c;</span><br><span class="line">&#125;GNUC_PACKED;</span><br></pre></td></tr></table></figure>

<p>此时 sizeof(struct C) 的值为7。</p>
<h2 id="4-2-栈内存对齐"><a href="#4-2-栈内存对齐" class="headerlink" title="4.2. 栈内存对齐"></a>4.2. 栈内存对齐</h2><p><strong>在VC/C++中，栈的对齐方式不受结构体成员对齐选项的影响，总是保持对齐在4字节边界上</strong>。</p>
<p>【例4】分析栈内存对齐方式：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(push, 1)  <span class="comment">//后面可改为1, 2, 4, 8</span></span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">StrtE</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> m1;</span><br><span class="line">    <span class="keyword">long</span> m2;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">pragma</span> pack(pop)</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> a;</span><br><span class="line">    <span class="keyword">short</span> b;</span><br><span class="line">    <span class="keyword">int</span> c;</span><br><span class="line">    <span class="keyword">double</span> d[<span class="number">2</span>];</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">StrtE</span> <span class="title">s</span>;</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;a    address:   %p\n&quot;</span>, &amp;a);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;b    address:   %p\n&quot;</span>, &amp;b);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;c    address:   %p\n&quot;</span>, &amp;c);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;d[0] address:   %p\n&quot;</span>, &amp;(d[<span class="number">0</span>]));</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;d[1] address:   %p\n&quot;</span>, &amp;(d[<span class="number">1</span>]));</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;s    address:   %p\n&quot;</span>, &amp;s);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;s.m2 address:   %p\n&quot;</span>, &amp;(s.m2));</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a    address:   0xbfc4cfff</span><br><span class="line">b    address:   0xbfc4cffc</span><br><span class="line">c    address:   0xbfc4cff8</span><br><span class="line">d[0] address:   0xbfc4cfe8</span><br><span class="line">d[1] address:   0xbfc4cff0</span><br><span class="line">s    address:   0xbfc4cfe3</span><br><span class="line">s.m2 address:   0xbfc4cfe4</span><br></pre></td></tr></table></figure>

<p>可以看出都是对齐到4字节，并且前面的char和short并没有被凑在一起（成4字节），这和结构体内的处理是不同的。</p>
<p>至于为什么输出的地址值是变小的，这是因为该平台下的栈是倒着“生长”的。</p>
<h2 id="4-3-位域对齐"><a href="#4-3-位域对齐" class="headerlink" title="4.3. 位域对齐"></a>4.3. 位域对齐</h2><h3 id="4-3-1-位域定义"><a href="#4-3-1-位域定义" class="headerlink" title="4.3.1. 位域定义"></a>4.3.1. 位域定义</h3><p>有些信息在存储时，并不需要占用一个完整的字节，而只需占几个或一个二进制位。例如在存放一个开关量时，只有0和1两种状态，用一位二进位即可。为了节省存储空间和处理简便，C语言提供了一种数据结构，称为<strong>位域</strong>或<strong>位段</strong>。</p>
<p>位域是一种特殊的结构成员或联合成员（即只能用在结构或联合中），用于指定该成员在内存存储时所占用的位数，从而在机器内更紧凑地表示数据。每个位域有一个域名，允许在程序中按域名操作对应的位，这样就可用一个字节的二进制位域来表示几个不同的对象。</p>
<p>位域定义与结构定义类似，其形式为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> 位域结构名</span></span><br><span class="line"><span class="class">       &#123;</span> 位域列表 &#125;;</span><br></pre></td></tr></table></figure>

<p>其中位域列表的形式为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">类型说明符位域名：位域长度</span><br></pre></td></tr></table></figure>

<p>位域的使用和结构成员的使用相同，其一般形式为：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">位域变量名.位域名</span><br></pre></td></tr></table></figure>

<p>位域允许用各种格式输出。</p>
<p><strong>位域在本质上就是一种结构类型，不过其成员是按二进位分配的</strong>。位域变量的说明与结构变量说明的方式相同，可先定义后说明、同时定义说明或直接说明。</p>
<p><strong>位域的使用主要为下面两种情况：</strong></p>
<ol>
<li>当机器可用内存空间较少而使用位域可大量节省内存时。例如：把结构作为大数组的元素时。</li>
<li>当需要把一结构体或联合映射成某预定的组织结构时。例如：需要访问字节内的特定位时。</li>
</ol>
<h3 id="4-3-2-对齐准则"><a href="#4-3-2-对齐准则" class="headerlink" title="4.3.2. 对齐准则"></a>4.3.2. 对齐准则</h3><p><code>位域成员不能单独被取sizeof值</code>。下面主要讨论含有位域的结构体的sizeof。</p>
<p>C99规定 int、unsigned int 和 bool 可以作为位域类型，但编译器几乎都对此作了扩展，允许其它类型的存在。位域作为嵌入式系统中非常常见的一种编程工具，优点在于压缩程序的存储空间。</p>
<p><strong>其对齐规则大致为：</strong></p>
<ol>
<li>如果相邻位域字段的类型相同，且其位宽之和小于类型的sizeof大小，则后面的字段将紧邻前一个字段存储，直到不能容纳为止；</li>
<li>如果相邻位域字段的类型相同，但其位宽之和大于类型的sizeof大小，则后面的字段将从新的存储单元开始，其偏移量为其类型大小的整数倍；</li>
<li><strong>如果相邻的位域字段的类型不同，则各编译器的具体实现有差异，VC6采取不压缩方式，Dev-C++和GCC采取压缩方式</strong>；</li>
<li>如果位域字段之间穿插着非位域字段，则不进行压缩；</li>
<li><strong>整个结构体的总大小为最宽基本类型成员大小的整数倍，而位域则按照其最宽类型字节数对齐</strong>。</li>
</ol>
<p>【例5】</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">BitField</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> element1  : <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">char</span> element2  : <span class="number">4</span>;</span><br><span class="line">    <span class="keyword">char</span> element3  : <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>位域类型为char，第1个字节仅能容纳下element1和element2，所以element1和element2被压缩到第1个字节中，而element3只能从下一个字节开始。因此 sizeof(BitField) 的结果为2。</p>
<p>【例6】</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">BitField1</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> element1   : <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">short</span> element2  : <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">char</span> element3   : <span class="number">7</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>由于相邻位域类型不同，在VC6中其sizeof为6，在Dev-C++中为2。</p>
<p>【例7】</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">BitField2</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> element1  : <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">char</span> element2  ;</span><br><span class="line">    <span class="keyword">char</span> element3  : <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>非位域字段穿插在其中，不会产生压缩，在VC6和Dev-C++中得到的大小均为3。</p>
<p>【例8】</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">StructBitField</span>&#123;</span></span><br><span class="line">    <span class="keyword">int</span> element1   : <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> element2   : <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">int</span> element3   : <span class="number">29</span>;</span><br><span class="line">    <span class="keyword">int</span> element4   : <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">char</span> element5  :<span class="number">2</span>;</span><br><span class="line">    <span class="keyword">char</span> stelement;  <span class="comment">//在含位域的结构或联合中也可同时说明普通成员</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>位域中最宽类型int的字节数为4，因此结构体按4字节对齐，在VC6中其sizeof为16。</p>
<h3 id="4-3-3-注意事项"><a href="#4-3-3-注意事项" class="headerlink" title="4.3.3. 注意事项"></a>4.3.3. 注意事项</h3><p>关于位域操作有几点需要注意：</p>
<p>1）<code>位域的地址不能访问，因此不允许将&amp;运算符用于位域</code>。不能使用指向位域的指针也不能使用位域的数组（数组是种特殊指针）。例如，scanf函数无法直接向位域中存储数据：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">BitField1</span> <span class="title">tBit</span>;</span></span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;tBit.element2); <span class="comment">//error: cannot take address of bit-field &#x27;element2&#x27;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可用scanf函数将输入读入到一个普通的整型变量中，然后再赋值给tBit.element2。</p>
<p>2）<code>位域不能作为函数返回的结果</code>。</p>
<p>3）<code>位域以定义的类型为单位，且位域的长度不能够超过所定义类型的长度</code>。例如：定义 int a:33 是不允许的。</p>
<p>4）<code>位域可以不指定位域名，但不能访问无名的位域</code>。</p>
<blockquote>
<p><strong>位域可以无位域名，只用作填充或调整位置，占位大小取决于该类型</strong>。例如，<code>char :0 表示整个位域向后推一个字节</code>，即该无名位域后的下一个位域从下一个字节开始存放，同理 <code>short :0</code> 和 <code>int :0</code> 分别表示整个位域向后推两个和四个字节。</p>
<p>当空位域的长度为具体数值N时(如 int :2)，该变量仅用来占位N位。</p>
</blockquote>
<p>【例9】</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">BitField3</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> element1  : <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">char</span>  :<span class="number">6</span>;</span><br><span class="line">    <span class="keyword">char</span> element3  : <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>结构体大小为3。因为element1占3位，后面要保留6位而char为8位，所以保留的6位只能放到第2个字节。同样element3只能放到第3字节。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">BitField4</span>&#123;</span></span><br><span class="line">    <span class="keyword">char</span> element1  : <span class="number">3</span>;</span><br><span class="line">    <span class="keyword">char</span>  :<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">char</span> element3  : <span class="number">5</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>长度为0的位域告诉编译器将下一个位域放在一个存储单元的起始位置。如上，编译器会给成员element1分配3位，接着跳过余下的4位到下一个存储单元，然后给成员element3分配5位。所以，上面的结构体大小为2 。</p>
<p>5）<strong>位域的表示范围：</strong></p>
<ul>
<li>位域的赋值不能超过其可以表示的范围。</li>
<li>位域的类型决定该编码能表示的值的结果。</li>
</ul>
<p>对于第二点，若位域为unsigned类型，则直接转化为正数；若非unsigned类型，则先判断最高位是否为1，若为1，则表示补码，则对其除符号位外的所有位取反再加一得到最后的结果数据（原码）。例如：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">unsigned</span> <span class="keyword">int</span> p:<span class="number">3</span> = <span class="number">111</span>;   <span class="comment">//p表示7</span></span><br><span class="line"><span class="keyword">int</span> p:<span class="number">3</span> = <span class="number">111</span>;            <span class="comment">//p 表示-1，对除符号位之外的所有位取反再加一</span></span><br></pre></td></tr></table></figure>

<p>6）<strong>带位域的结构在内存中各个位域的存储方式取决于编译器，既可从左到右也可从右到左存储。</strong></p>
<p>【例10】在VC6下执行下面的代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span>&#123;</span><br><span class="line">    <span class="class"><span class="keyword">union</span>&#123;</span></span><br><span class="line">        <span class="keyword">int</span> i;</span><br><span class="line">        <span class="class"><span class="keyword">struct</span>&#123;</span></span><br><span class="line">            <span class="keyword">char</span> a : <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">char</span> b : <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">char</span> c : <span class="number">2</span>;</span><br><span class="line">        &#125;bits;</span><br><span class="line">    &#125;num;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Input an integer for i(0~15): &quot;</span>);</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;num.i);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;i = %d, cba = %d %d %d\n&quot;</span>, num.i, num.bits.c, num.bits.b, num.bits.a);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br></pre></td></tr></table></figure>

<p>输入i值为11，则输出为i = 11, cba = -2 -1 -1。</p>
<p>Intel x86 处理器按小字节序存储数据，所以bits中的位域在内存中放置顺序为ccba。当num.i置为11时，bits的最低有效位(即位域a)的值为1，a、b、c按低地址到高地址分别存储为10、1、1(二进制)。</p>
<p><code>但为什么最后的打印结果是a=-1而不是1？</code></p>
<p>因为位域a定义的类型signed char是有符号数，所以尽管a只有1位，仍要进行符号扩展。1做为补码存在，对应原码-1。</p>
<p>如果将a、b、c的类型定义为unsigned char，即可得到cba = 2 1 1。1011即为11的二进制数。</p>
<blockquote>
<p>注：C语言中，不同的成员使用共同的存储区域的数据构造类型称为联合(或共用体)。联合占用空间的大小取决于类型长度最大的成员。联合在定义、说明和使用形式上与结构体相似。</p>
</blockquote>
<p>7）<strong>位域的实现会因编译器的不同而不同，使用位域会影响程序可移植性</strong>。因此如无必要，最好不要使用位域。</p>
<p>8）<strong>尽管使用位域可以节省内存空间，但却增加了处理时间</strong>。当访问各个位域成员时，需要把位域从它所在的字中分解出来或反过来把一值压缩存到位域所在的字位中。</p>
<h1 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h1><p>让我们回到引言部分的问题。</p>
<p>缺省情况下，C/C++编译器默认将结构、栈中的成员数据进行内存对齐。因此，引言程序输出就变成”c1 -&gt; 0, s -&gt; 2, c2 -&gt; 4, i -&gt; 8”。</p>
<p>编译器将未对齐的成员向后移，将每一个都成员对齐到自然边界上，从而也导致整个结构的尺寸变大。尽管会牺牲一点空间(成员之间有空洞)，但提高了性能。</p>
<p>也正是这个原因，引言例子中sizeof(T_ FOO)为12，而不是8。</p>
<p>总结说来，就是：<strong>在结构体中，综合考虑变量本身和指定的对齐值；在栈上，不考虑变量本身的大小，统一对齐到4字节</strong>。</p>
<blockquote>
<p><strong>说明：</strong> 本文转载自 <a target="_blank" rel="noopener" href="https://www.cnblogs.com/clover-toeic/p/3853132.html">https://www.cnblogs.com/clover-toeic/p/3853132.html</a></p>
</blockquote>
<hr>
<p>欢迎关注我的微信公众号【数据库内核】：分享主流开源数据库和存储引擎相关技术。</p>
<img src="https://dbkernel-1306518848.cos.ap-beijing.myqcloud.com/wechat/my-wechat-official-account.png" width="400" height="400" alt="欢迎关注公众号数据库内核" align="center"/>

<table>
<thead>
<tr>
<th>标题</th>
<th>网址</th>
</tr>
</thead>
<tbody><tr>
<td>GitHub</td>
<td><a href="https://dbkernel.github.io/">https://dbkernel.github.io</a></td>
</tr>
<tr>
<td>知乎</td>
<td><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/dbkernel/posts">https://www.zhihu.com/people/dbkernel/posts</a></td>
</tr>
<tr>
<td>思否（SegmentFault）</td>
<td><a target="_blank" rel="noopener" href="https://segmentfault.com/u/dbkernel">https://segmentfault.com/u/dbkernel</a></td>
</tr>
<tr>
<td>掘金</td>
<td><a target="_blank" rel="noopener" href="https://juejin.im/user/5e9d3ed251882538083fed1f/posts">https://juejin.im/user/5e9d3ed251882538083fed1f/posts</a></td>
</tr>
<tr>
<td>开源中国（oschina）</td>
<td><a target="_blank" rel="noopener" href="https://my.oschina.net/dbkernel">https://my.oschina.net/dbkernel</a></td>
</tr>
<tr>
<td>博客园（cnblogs）</td>
<td><a target="_blank" rel="noopener" href="https://www.cnblogs.com/dbkernel">https://www.cnblogs.com/dbkernel</a></td>
</tr>
</tbody></table>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="http://dbkernel.github.io/2014/07/21/c-language-byte-alignment-problem-in-detail-part-1/" title="程序人生 | C语言字节对齐问题详解 - 对齐/字节序/位序/网络序等（上）" target="_blank" rel="external">http://dbkernel.github.io/2014/07/21/c-language-byte-alignment-problem-in-detail-part-1/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN 许可协议</a>，转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/dbkernel" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="../../../../images/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/dbkernel" target="_blank"><span class="text-dark">DBKernel</span><small class="ml-1x">资深数据库开发工程师</small></a></h3>
        <div>目前从事云数据库MySQL/PostgreSQL的研发工作，曾做过PGXC、Greenplum等分布式数据库的内核开发。热衷于研究主流数据库架构、源码，对关系型数据库 MySQL/PostgreSQL及分布式数据库有深入研究。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
           
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="../c-language-byte-alignment-problem-in-detail-part-2/" title="程序人生 | C语言字节对齐问题详解 - 对齐/字节序/位序/网络序等（下）"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="../../10/makefile-common-templates/" title="程序人生 | Makefile 常用模板 - 静态链接库/动态链接库/可执行文件"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span>[&nbsp;</span><span>文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span>]</span>
      </a>
    </li>
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,qzone,facebook,twitter,linkedin" data-mobile-sites="weibo,qq,wechat,qzone,linkedin"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="../../../../images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="../../../../images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="../../../../https:/github.com/dbkernel" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="../../../../atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2022 DBKernel
        
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="../../../../js/plugin.min.js"></script>


<script src="../../../../js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '../../../../content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="../../../../js/insight.js"></script>






   
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





   
    
  <!-- <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"> -->
  <script src="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>
  <script type="text/javascript">
  var gitalk = new Gitalk({
    clientID: '642675de9efee853bde8',
    clientSecret: 'e481d901d83ac31b4041437ec30a4fd00d112cfa',
    repo: 'dbkernel/gitalk-comment',
    owner: 'dbkernel',
    admin: ['dbkernel1989'],
    id: md5(location.pathname),
    distractionFreeMode: true
  })
  gitalk.render('comments')
  </script>

      






    <script defer>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?bf7f972e25b6a36ff4b828ba0214e515";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>



</body>
</html>